package me.j360.springboot.simple.bean.search;

import me.j360.springboot.simple.bean.BaseEnum;
import org.springframework.util.Assert;

/**
 * 说明：
 * Bean类 - 查询分页条件
 *
 * ============================================================================
 * 版权所有 2015 qiushihua。
 *
 * @author qiushihua
 * @version 0.1 2015-07-22
 * ============================================================================
 */
public class Page {

    public static final Integer DEFAULT_PAGE_NUMBER = 1;// 默认当前页
    public static final Integer DEFAULT_PAGE_SIZE = 20;// 默认每页记录数
    public static final BaseEnum.ResultType DEFAULT_RESULT_TYPE = BaseEnum.ResultType.list;// 默认返回list

    public static final Integer MAX_PAGE_SIZE = 500;// 最大每页记录数

    private final Integer pageNumber;
    private final Integer pageSize;
    private final BaseEnum.ResultType resultType;

    public Page(Integer pageNumber, Integer pageSize, BaseEnum.ResultType resultType) {
        this.pageNumber = pageNumber;
        this.pageSize = pageSize;
        this.resultType = resultType;
    }

    public Integer getPageNumber() {
        return pageNumber;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public BaseEnum.ResultType getResultType() {
        return resultType;
    }

    private static Builder newBuilder() {
        return new Builder();
    }

    public static Page simplePage() {
        return newBuilder().setPageNumber(DEFAULT_PAGE_NUMBER).setPageSize(DEFAULT_PAGE_SIZE).setResultType(DEFAULT_RESULT_TYPE).build();
    }

    public static Page page(Integer pageNumber, Integer pageSize) {
        return newBuilder().setPageNumber(pageNumber).setPageSize((pageSize > MAX_PAGE_SIZE) ? MAX_PAGE_SIZE : pageSize).setResultType(BaseEnum.ResultType.list).build();
    }

    public static Page list() {
        return newBuilder().setPageNumber(0).setPageSize(DEFAULT_PAGE_SIZE).setResultType(BaseEnum.ResultType.list).build();
    }

    public static Page uniqueResult() {
        return newBuilder().setPageNumber(0).setPageSize(DEFAULT_PAGE_SIZE).setResultType(BaseEnum.ResultType.uniqueResult).build();
    }

    public static class Builder {

        private Integer pageNumber;
        private Integer pageSize;
        private BaseEnum.ResultType resultType;

        public Builder setPageNumber(Integer pageNumber) {
            this.pageNumber = pageNumber;
            return this;
        }

        public Builder setPageSize(Integer pageSize) {
            this.pageSize = pageSize;
            return this;
        }

        public Builder setResultType(BaseEnum.ResultType resultType) {
            this.resultType = resultType;
            return this;
        }

        public Page build() {
            Assert.isTrue(pageNumber >= 0, "pageNumber 必须大于等于 0");
            Assert.isTrue(pageSize > 0, "pageSize 必填大于 0");
            Assert.notNull(resultType, "resultType 不能为空");
            return new Page(pageNumber, pageSize, resultType);
        }

    }

}
